package com.study.ssm.aop.spring;

import com.study.ssm.aop.proxy.UserService;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @author zhoujunlin
 * @date 2023年07月24日 14:34
 * @desc
 */
public class ProxyBeanPostProcessor implements BeanPostProcessor {

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        if (bean instanceof UserService) {
            InvocationHandler invocationHandler = new InvocationHandler() {
                @Override
                public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                    System.out.println("ProxyBeanPostProcessor.invoke   before log============>");
                    return method.invoke(bean, args);
                }
            };
            return Proxy.newProxyInstance(ProxyBeanPostProcessor.class.getClassLoader(),
                    bean.getClass().getInterfaces(), invocationHandler);
        }
        return bean;
    }
}
